# from micaps.micaps import Micaps
import datetime
from os.path import join as pathjoin


def NextDay(y, m, d):
    date = datetime.date(y, m, d)
    next = date + datetime.timedelta(1)
    return next.year, next.month, next.day


class Shift():
    def __init__(self, out12Path):
        self.outPath = out12Path
        self.r_max192 = None
        self.r_min192 = None

    def WriteMax(self, mi, file, r):
        issue, preds = file.split('.')
        y = int('20' + issue[:2])
        m = int(issue[2:4])
        d = int(issue[4:6])
        t = int(issue[6:])
        p = int(preds)
        if t == 8:
            t = 20
            p -= 24
            # head tail proccess
            if p == 192:
                self.r_max192 = r
            if p == 216:
                _p = 240
                if self.r_max192 is None:
                    _r = r
                else:
                    _r = (r + self.r_max192) / 2
                self.Write(mi, 'TMAX', y, m, d, t, _p, _r)
        elif t == 20:
            y, m, d = NextDay(y, m, d)
            t = 8
        else:
            print('write_max err!')

        if p:
            self.Write(mi, 'TMAX', y, m, d, t, p, r)

    def WriteMin(self, mi, file, r):
        issue, preds = file.split('.')
        y = int('20' + issue[:2])
        m = int(issue[2:4])
        d = int(issue[4:6])
        t = int(issue[6:])
        p = int(preds)
        if t == 8:
            t = 20
        elif t == 20:
            y, m, d = NextDay(y, m, d)
            t = 8
            p -= 24
            # head tail proccess
            if p <= 0:
                return
            if p == 192:
                self.r_min192 = r
            if p == 216:
                _p = 240
                if self.r_min192 is None:
                    _r = r
                else:
                    _r = r + (r - self.r_min192) / 2
                self.Write(mi, 'TMIN', y, m, d, t, _p, _r)
        else:
            print('write_min err!')
            return
        if p:
            self.Write(mi, 'TMIN', y, m, d, t, p, r)

    def Write(self, mi, tcls, y, m, d, t, p, r):
        file = str.format('%02d%02d%02d%02d.%03d' % (y, m, d, t, p))[2:]
        pathFile = pathjoin(self.outPath, tcls, file)
        # print(pathFile)
        head1 = str.format('%d %d %d %d %d %d\n' % (y, m, d, t, p, 0))
        mi.write(pathFile, r, head1)
